package net.xdclass.controller;

import cn.felord.payment.wechat.v3.WechatPayCallback;
import cn.felord.payment.wechat.v3.model.ResponseSignVerifyParams;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.config.WechatPayConfig;
import net.xdclass.service.ProductOrderService;
import net.xdclass.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 小滴课堂,愿景：让技术不再难学
 *
 * @Description
 * @Author 二当家小D
 * @Remark 有问题直接联系我，源码-笔记-技术交流群
 * @Version 1.0
 **/

@Controller
@RequestMapping("/api/callback/order/v1/")
@Slf4j
public class PayCallbackController {


	@Autowired
	private WechatPayConfig wechatPayConfig;


	@Autowired
	private ProductOrderService productOrderService;


	@Resource
	private WechatPayCallback wechatPayCallback;




	/**
	 * * 获取报文
	 * <p>
	 * * 验证签名（确保是微信传输过来的）
	 * <p>
	 * * 解密（AES对称解密出原始数据）
	 * <p>
	 * * 处理业务逻辑
	 * <p>
	 * * 响应请求
	 *
	 * @param request
	 * @return
	 */
	@SneakyThrows
	@PostMapping("transaction")
	public Map<String, String> transactionCallback(@RequestHeader("Wechatpay-Serial") String wechatpaySerial,
	                                          @RequestHeader("Wechatpay-Signature") String wechatpaySignature,
	                                          @RequestHeader("Wechatpay-Timestamp") String wechatpayTimestamp,
	                                          @RequestHeader("Wechatpay-Nonce") String wechatpayNonce,
	                                          HttpServletRequest request) {

		String body = request.getReader().lines().collect(Collectors.joining());
		// 对请求头进行验签 以确保是微信服务器的调用
		ResponseSignVerifyParams params = new ResponseSignVerifyParams();
		params.setWechatpaySerial(wechatpaySerial);
		params.setWechatpaySignature(wechatpaySignature);
		params.setWechatpayTimestamp(wechatpayTimestamp);
		params.setWechatpayNonce(wechatpayNonce);
		params.setBody(body);
		log.info("回调发生了，{}", JSONUtil.toJsonStr(params));

		return wechatPayCallback.transactionCallback(params, data -> {
			//TODO 对回调解析的结果进行消费  需要保证消费的幂等性 微信有可能多次调用此接口
			productOrderService.processCallBack(params,data);
		});
//		return null;
	}





}
